﻿using System;
using System.Linq;
using System.Web.Mvc;

namespace ExtendedMvc.Elements {
	public class GridDataColumn<TModel> : GridColumnBase<GridDataColumn<TModel>, TModel>, IGridDataColumn<TModel> where TModel : class {
		private bool _sortable = true;
		//private string _memberName;
		private readonly Func<TModel, object> _value;
		private string _format;
		private ModelMetadata _metadata;

		public GridDataColumn(Func<TModel, object> value, string name, ModelMetadata metadata)
			: base(name) {
			_value = value;
			_metadata = metadata;
		}

		public bool Sortable { get { return _sortable; } }

		//public string memberName { get { return _memberName; } }

		protected Func<TModel, object> value { get { return _value; } }

		IGridDataColumn<TModel> IGridDataColumn<TModel>.Sortable(bool value) {
			_sortable = value;
			return this;
		}

		//public IGridDataColumn<TModel> MemberName(string value) {
		//    _memberName = value;
		//    return this;
		//}

		public IGridDataColumn<TModel> Format(string format) {
			_format = format;
			return this;
		}

		public override object GetHeader() {
			var result = base.GetHeader();
			if (result != null) return result;
			result = Name;
			if (result != null) {
				var colMetadata = _metadata.Properties.SingleOrDefault(p => p.PropertyName == result.ToString());
				if (colMetadata != null && colMetadata.DisplayName != null) result = colMetadata.DisplayName;
			}
			return result;
		}

		public override object GetData(TModel source) {
			if (!showIf(source)) return null;
			var value = _value(source);
			if (!string.IsNullOrEmpty(_format)) value = string.Format(_format, value);
			var memberName = Name;
			if (memberName != null) {
				var colMetadata = _metadata.Properties.SingleOrDefault(p => p.PropertyName == memberName);
				if (value == null && colMetadata != null && colMetadata.NullDisplayText != null) value = colMetadata.NullDisplayText;
			}
			//if (_htmlEncode && value != null) value = HttpUtility.HtmlEncode(value.ToString());
			return value;
		}
	}
}
